package day01;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author chenshijie
 * @date 2023/12/14 15:17
 */

public class IOServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8001);
        System.out.println("监听端口8001中...");
        // 接收新链接线程
        new Thread(() -> {
            while (true) {
                try {
                    // (1)阻塞方法获取新连接
                    System.out.println("正在等待客户端接入");
                    Socket socket = serverSocket.accept();

//                    while (true) {
                        // (2)为每一个新连接都创建一个新线程，负责读取数据
                    new Thread(() -> {
                        try {
                            int len;
                            byte[] data = new byte[1024];
                            InputStream inputStream = socket.getInputStream();
                            // (3)按字节流读取数据
                            while ((len = inputStream.read(data)) != -1) {
                                System.out.println(new String(data, 0, len));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
//                  }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }
}
